import { _decorator, Component, Label, Sprite, resources, SpriteFrame, Input, input, EventKeyboard, KeyCode } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Dialog')
export class Dialog extends Component {

    @property({ type: Sprite })
    avatar: Sprite;

    @property({ type: Label })
    nameLabel: Label;

    @property({ type: Label })
    textLabel: Label;

    private _textIndex: number;

    private _textDataArr: TextData[];

    //对话的播放速度, 用来控制0.1s播放一次
    private _tt: number;

    //当前对话是否结束
    private _textEnd: boolean;

    //当前这段话的所有文本
    private _nowText: string;

    protected onDestroy(): void {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    protected onLoad(): void {
        this.init()

        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    init() {
        this._textDataArr = [];
        this._textDataArr.push(new TextData("勇者", "骷髅王，你的恶行必须停止！", "role/hero/spriteFrame"));
        this._textDataArr.push(new TextData("骷髅王", "让我们来见识一下你所谓的力量吧！", "role/skeletonKing/spriteFrame"));

        //初始化时要播放第一段对话
        this._textEnd = true;
        this._nowText = null;
        this._tt = 0;

        this._textIndex = -1;
        this.node.active = true;

        this.nextTextData();
    }


    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.SPACE:
                this.nextTextData()
                break;
        }
    }

    nextTextData() {
        if (!this._textEnd) return;
        if (++this._textIndex < this._textDataArr.length) {
            this.setTextDate(this._textDataArr[this._textIndex]);
        } else {
            this.closeDialog()
        }
    }

    closeDialog() {
        this.node.active = false;
    }

    setTextDate(textData: TextData) {
        if (!this._textEnd) return;
        this._textEnd = false;

        this.nameLabel.string = textData.name;
        this.textLabel.string = "";

        this._nowText = textData.content;

        resources.load(textData.url, SpriteFrame, (err: any, spFrame: SpriteFrame) => {
            this.avatar.spriteFrame = spFrame;
        });
    }


    update(deltaTime: number) {
        if (!this._nowText) return;
        this._tt += deltaTime;

        if (this._tt >= 0.05) {
            if (this.textLabel.string.length < this._nowText.length) {
                this.textLabel.string = this._nowText.slice(0, this.textLabel.string.length + 1)
            } else {
                this._textEnd = true;
                this._nowText = null;
            }
            this._tt = 0;
        }
    }
}

class TextData {
    name: string;
    content: string;
    url: string;

    constructor(name: string, content: string, url: string) {
        this.name = name;
        this.content = content;
        this.url = url;
    }
}


